
import { useEffect, useRef, useState } from 'react'
import { NavBar, Toast, Form, Button, Input, TextArea, Picker, Selector, ImageUploader } from 'antd-mobile'
import { useNavigate, useLocation } from 'react-router-dom'
import { getArticlesInfo } from '@/api/home'
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader'
import userStore from '@/store/userStore'
import { Image, Upload } from 'antd';
import { postSaveChannels, putSaveChannels } from '@/api/create'
import './index.scss'
import { PlusOutlined } from '@ant-design/icons';
const Create = () => {

  const [title, setTitle] = useState('创建');
  const [titleData, setTitleData] = useState('');//form表单中的title
  const [content, setContent] = useState('');
  const [type, setType] = useState(0)//图片数量
  const [visible, setVisible] = useState(false);
  const [channel, setChannel] = useState([{ label: '加载失败', value: -1 }])
  const [channel_id, setChannel_id] = useState<number>(-1)
  const { channelList } = userStore()
  // const [fileList, setFileList] = useState<ImageUploadItem[]>([
  // {
  // 
  // },
  // ])
  const navigate = useNavigate()
  const location = useLocation()
  const id = location.state?.id;
  const [form] = Form.useForm()

  const back = () => {
    navigate('/home')
  }


  const getInfo = async () => {
    let result = await getArticlesInfo(id);
    if (result && result.status == 200) {

      setTitleData(result.data.data.title)
      setChannel_id(result.data.data.channel_id)
      setType(result.data.data.cover.type)
      setContent(result.data.data.content)

      //  form.setFieldsValue({
      //   title: result.data.data.title,
      //   channel_id: result.data.data.channel_id,
      //   status: result.data.data.cover.type,
      //   content: result.data.data.content,
      // });

    } else {
      Toast.show({
        icon: 'fail',
        content: '获取文章信息失败',
      })
    }
  }
  useEffect(() => {
    if (id) {
      setTitle('修改')
      getInfo()
    }
    setChannel(channelList.map(item => { return { label: item.name, value: item.id } }))
  }, [])

useEffect(()=>{
  if(fileList.length>type){
    let l=[];
    for(let i=0;i<type;i++){
      l.push(fileList[i])
    }
    setFileList(l)
  }
},[type])

  const saveAndPut = async () => {
    const images = fileList.map(item=> item.response.data.url);
  
    let data = {
      title: titleData,
      channel_id: channel_id,
      content: content,
      cover: {
        type:type ,
        images: images
      }
    }
    let result;
    if (id) {
      result = await putSaveChannels(data, id);
      if (result && result.status == 200) {
        Toast.show({
          icon: 'success',
          content: '上传文章信息成功',
        })
        navigate('/Manage')
      } else {
        Toast.show({
          icon: 'fail',
          content: '上传文章信息失败',
        })
      }

    } else {
      result = await postSaveChannels(data);
      if (result && result.status == 200) {
        Toast.show({
          icon: 'success',
          content: '上传文章信息成功',
        })
        clear()
      } else {
        Toast.show({
          icon: 'fail',
          content: '上传文章信息失败',
        })
      }

    }
  }

  const clear = () => {
    form.resetFields();
    setTitleData('');   // 清空标题
    setContent('');     // 清空内容
    setChannel_id(-1);  // 重置分类
    setType(0);
  }

  //------------------------------图片上传逻辑-------------------------------------------
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<string[]>([]); // 上传图片的列表
  //const [temp,setTemp]= useState<[]>([]);
  const getBase64 = (file:any) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  })

  const handleChange = async ({ file, fileList: newFileList }) => {
   setFileList(newFileList)
  };

  const handleRemove = (file:any) => {
    const updatedList = fileList.filter((item) => item.uid !== file.uid);
    setFileList(updatedList);
  };

  const handlePreview = async (file:any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
  };

  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
      }}
      type="button"
    >
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </button>
  );

  return (
    <div className='container2'>
      <NavBar style={{ height: '3rem', fontWeight: "600", borderBottom: '1px #eee solid', }}
        back='首页' onBack={back}>{title}文章</NavBar>


      <Form
        form={form}
        layout='horizontal'
        footer={
          <>
            <Button block onClick={() => saveAndPut()} type='submit' color='primary' size='large'>
              提交
            </Button>

          </>
        }
      >

        <Form.Item

          label='标题'
          rules={[{ required: true, message: '标题不能为空' }]}
        >
          <Input onChange={(value) => setTitleData(value)} value={titleData} placeholder='请输入标题' />
        </Form.Item>

        <Form.Item label='分类' childElementPosition='right'>
          <div className='cl_id'>
            {channel_id > -1 && <p className='sel'>已选择:{channelList.find(item => item.id == channel_id).name}</p>}
            <Button className='but' onClick={() => setVisible(true)}>选择</Button>

          </div>
          <Picker
            columns={[channel]}
            visible={visible}
            onClose={() => {
              setVisible(false)
            }}
            value={[channel_id]}
            onConfirm={(value) => {
              setChannel_id(value[0])
            }}
          />
        </Form.Item>

        <Form.Item label='状态' childElementPosition='normal'>
          <Selector
            options={options}
            value={[type]}
            onChange={(arr) => setType(arr[0])}
            style={{marginBottom:"1rem"}}
          />

          <Upload
            action={'http://geek.itheima.net/v1_0/upload'}
            listType="picture-card"
            fileList={fileList}
            name="image"//必须得有他
            maxCount={type}
            onChange={handleChange}
            onPreview={handlePreview}
            onRemove={handleRemove}
            
          // onRemove={rem}
          >
            {fileList.length >= type ? null : uploadButton}
          </Upload>

          {previewImage && (
            <Image
              wrapperStyle={{
                display: 'none',
              }}
              preview={{
                visible: previewOpen,
                onVisibleChange: (visible) => setPreviewOpen(visible),
                afterOpenChange: (visible) => !visible && setPreviewImage(''),
              }}
              src={previewImage}
            />
          )}

        </Form.Item>

        <Form.Item
          rules={[{ required: true, message: '正文不能为空' }]}
          label='正文'

        >
          <TextArea
            onChange={(value) => setContent(value)}
            value={content}
            placeholder='请输入内容'
            maxLength={1000}
            rows={4}
            showCount
          />
        </Form.Item>
      </Form>
      <div className='clear' >
        <Button block onClick={() => clear()} type='submit' color='warning' size='large'>
          清空
        </Button>
      </div>
    </div>
  )
}
export default Create

const options = [
  {
    label: '无图',
    value: 0,
  },
  {
    label: '单图',
    value: 1,
  },
  {
    label: '三图',
    value: 3,
  },
]